'use client';

import { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useTheme } from '@/providers/theme-provider';
import { signOut, useSession } from '@/lib/auth-client';
import { useToast } from '@/components/ui/ToastProvider';
import { 
  Bell, 
  Search, 
  Menu, 
  User, 
  ChevronDown,
  Calendar,
  FileText,
  Users,
  BarChart3,
  Settings,
  LogOut
} from 'lucide-react';
import { DashBoard, Application, Chart, Stacks2, Cart } from '../svg/Icons';

const menuItems = [
  {
    id: 'dashboard',
    icon: DashBoard,
    label: 'Dashboard',
    subItems: [
      { id: 'overview', label: 'Overview', href: '/dashboard' },
      { id: 'analytics', label: 'Analytics', href: '/analytics' },
      { id: 'reports', label: 'Reports', href: '/reports' },
      { id: 'insights', label: 'Insights', href: '/insights' }
    ]
  },
  {
    id: 'project',
    icon: Stacks2,
    label: 'Project',
    subItems: [
      { id: 'project-overview', label: 'Project Overview', href: '/project-overview' },
      { id: 'tasks', label: 'Tasks', href: '/project/tasks' },
      { id: 'team', label: 'Team', href: '/project/team' },
      { id: 'calendar', label: 'Calendar', href: '/project/calendar' },
      { id: 'documents', label: 'Documents', href: '/project/documents' }
    ]
  }
];

interface ThreeLayerDashboardLayoutProps {
  children: React.ReactNode;
  userId: string;
}

export default function ThreeLayerDashboardLayout({ children, userId }: ThreeLayerDashboardLayoutProps) {
  const [activeMenu, setActiveMenu] = useState('project');
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isUserDropdownOpen, setIsUserDropdownOpen] = useState(false);
  const { mode, toggleMode } = useTheme();

  const router = useRouter();
  const { showSuccess, showError } = useToast();
  const { data: session } = useSession();
  const userDropdownRef = useRef<HTMLDivElement>(null);

  const activeMenuItem = menuItems.find(item => item.id === activeMenu);

  // 处理点击外部关闭下拉菜单
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (userDropdownRef.current && !userDropdownRef.current.contains(event.target as Node)) {
        setIsUserDropdownOpen(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 处理退出登录
  const handleLogout = async () => {
    try {
      await signOut();
      showSuccess('退出成功', '已安全退出登录');
      router.push('/auth/login');
    } catch (error) {
      showError('退出失败', '请重试');
    }
  };

  // 处理账号信息页面
  const handleAccountInfo = () => {
    setIsUserDropdownOpen(false);
    router.push(`/${userId}/profile`);
  };

  // 处理跳转到dashboard
  const handleDashboard = () => {
    router.push(`/${userId}/dashboard`);
  };

  return (
    <div className="flex h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
      {/* Left Sidebar - Main Menu Icons (16px) */}
      <div className="w-16 bg-white dark:bg-slate-800 border-r border-dashed border-slate-200 dark:border-slate-700 flex flex-col shadow-lg">
        {/* Logo Area */}
        <div className="h-16 flex items-center justify-center border-b border-slate-200 dark:border-slate-700">
          <button
            onClick={handleDashboard}
            className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center shadow-lg hover:bg-primary/90 transition-all duration-200 hover:scale-105"
          >
            <span className="text-primary-foreground font-bold text-sm">D</span>
          </button>
        </div>

        {/* Menu Items */}
        <div className="flex-1 py-4">
          <nav className="space-y-2 px-2">
            {menuItems.map((item) => {
              const IconComponent = item.icon;
              const isActive = activeMenu === item.id;
              
              return (
                <button
                  key={item.id}
                  onClick={() => setActiveMenu(item.id)}
                  className={`w-12 h-12 rounded-xl flex items-center justify-center transition-all duration-200 group relative ${
                    isActive
                      ? 'bg-primary text-primary-foreground shadow-lg scale-105'
                      : 'text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700'
                  }`}
                  title={item.label}
                >
                  <IconComponent className="w-5 h-5" />
                  
                  {/* Tooltip */}
                  <div className="absolute left-full ml-3 px-2 py-1 bg-slate-800 dark:bg-slate-700 text-white text-xs rounded-md opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none whitespace-nowrap z-50">
                    {item.label}
                  </div>
                </button>
              );
            })}
          </nav>
        </div>



        {/* User Avatar */}
        <div className="p-2 border-t border-slate-200 dark:border-slate-700">
          <button
            onClick={handleLogout}
            className="w-12 h-12 bg-primary rounded-xl flex items-center justify-center shadow-lg group relative hover:bg-red-500 transition-all duration-200 hover:scale-105"
          >
            <User className="w-5 h-5 text-primary-foreground" />
            
            {/* User Tooltip */}
            <div className="absolute left-full ml-3 px-2 py-1 bg-slate-800 dark:bg-slate-700 text-white text-xs rounded-md opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none whitespace-nowrap z-50">
              退出登录
            </div>
          </button>
        </div>
      </div>

             {/* Middle Sidebar - Secondary Menu (264px) */}
       <div className="w-64 bg-white dark:bg-slate-800 border-r border-slate-200 dark:border-slate-700 shadow-lg">
        {/* Header */}
        <div className="h-16 px-6 border-b border-slate-200 dark:border-slate-700 flex items-center">
          <h2 className="text-lg font-semibold text-slate-800 dark:text-slate-200">
            {activeMenuItem?.label}
          </h2>
        </div>

                 {/* Sub Menu Items */}
         <div className="py-4">
           <nav className="space-y-1 px-4">
             {activeMenuItem?.subItems.map((subItem) => {
               return (
                 <div
                   key={subItem.id}
                   className="flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 group hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 cursor-default"
                 >
                   {subItem.label}
                 </div>
               );
             })}
           </nav>
         </div>

        

        
      </div>

      {/* Main Content Area */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Top Navigation */}
        <header className="h-16 bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700 shadow-sm">
          <div className="h-full px-6 flex items-center justify-between">
            {/* Left Side */}
            <div className="flex items-center space-x-4">
              <button className="lg:hidden p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700">
                <Menu className="w-5 h-5" />
              </button>
              
              {/* Search */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                <input
                  type="text"
                  placeholder="Search..."
                  className="pl-10 pr-4 py-2 w-80 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-violet-500 focus:border-transparent"
                />
              </div>
            </div>

            {/* Right Side */}
            <div className="flex items-center space-x-4">
              {/* Language Selector */}
              <div className="flex items-center space-x-2 px-3 py-2 bg-slate-50 dark:bg-slate-700 rounded-lg">
                <div className="w-5 h-3 bg-gradient-to-r from-red-500 to-blue-500 rounded-sm"></div>
                <span className="text-sm font-medium text-slate-700 dark:text-slate-300">En</span>
              </div>

                             {/* Theme Toggle */}
               <button
                 onClick={toggleMode}
                 className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"
               >
                 {mode === 'dark' ? '🌞' : '🌙'}
               </button>

              {/* Notifications */}
              <div className="relative">
                <button className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors">
                  <Bell className="w-5 h-5 text-slate-600 dark:text-slate-400" />
                </button>
                <div className="absolute -top-1 -right-1 w-5 h-5 bg-red-500 rounded-full flex items-center justify-center">
                  <span className="text-xs text-white font-medium">1</span>
                </div>
              </div>

              

                             {/* User Profile */}
               <div className="relative" ref={userDropdownRef}>
                 <button
                   onClick={() => setIsUserDropdownOpen(!isUserDropdownOpen)}
                   className="flex items-center space-x-3 pl-4 border-l border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-700 rounded-lg py-2 transition-colors"
                 >
                   <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center shadow-lg">
                     <span className="text-primary-foreground font-medium text-sm">
                       {session?.user?.email?.charAt(0).toUpperCase() || 'A'}
                     </span>
                   </div>
                   <ChevronDown className={`w-4 h-4 text-slate-400 transition-transform duration-200 ${
                     isUserDropdownOpen ? 'rotate-180' : ''
                   }`} />
                 </button>

                 {/* Dropdown Menu */}
                 {isUserDropdownOpen && (
                   <div className="absolute right-0 top-full mt-2 w-64 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg shadow-lg z-50">
                     {/* User Info Header */}
                     <div className="px-4 py-3 border-b border-slate-200 dark:border-slate-700">
                       <div className="flex items-center space-x-3">
                         <div className="w-10 h-10 bg-primary rounded-lg flex items-center justify-center shadow-lg">
                           <span className="text-primary-foreground font-medium">
                             {session?.user?.email?.charAt(0).toUpperCase() || 'A'}
                           </span>
                         </div>
                         <div className="flex-1 min-w-0">
                           <p className="text-sm font-medium text-foreground truncate">
                             {session?.user?.email || 'User'}
                           </p>
                           <p className="text-xs text-muted-foreground truncate">
                             Premium Account
                           </p>
                         </div>
                       </div>
                     </div>

                     {/* Menu Items */}
                     <div className="py-2">
                       <button
                         onClick={handleAccountInfo}
                         className="w-full flex items-center space-x-3 px-4 py-2 text-sm text-foreground hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors"
                       >
                         <Settings className="w-4 h-4 text-muted-foreground" />
                         <span>账号信息</span>
                       </button>
                       
                       <button
                         onClick={handleLogout}
                         className="w-full flex items-center space-x-3 px-4 py-2 text-sm text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
                       >
                         <LogOut className="w-4 h-4" />
                         <span>退出登录</span>
                       </button>
                     </div>
                   </div>
                 )}
               </div>
            </div>
          </div>
        </header>

        {/* Main Content */}
        <main className="flex-1 overflow-auto bg-slate-50 dark:bg-slate-900">
          <div className="p-6">
            {children}
          </div>
        </main>
      </div>
    </div>
  );
} 